//
//  XMPicwordSearchView.m
//  XMJJ_zmy
//
//  Created by 丁浩 on 2025/7/15.
//

#import "XMPicwordSearchView.h"
#import "XMPicwordCell.h"
#import "WaterfallFlowLayout.h"
#import "XMAddFriendCell.h"
#import "XMSearchScreenView.h"
#import "XMSearchHistoryView.h"

#define XMHISTORYSEARCHKEY        @"picwordSearchHistory"

@interface XMPicwordSearchView () <UICollectionViewDelegate, UICollectionViewDataSource, WaterfallFlowLayoutDelegate, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UITableView *tbl;
@property (nonatomic, strong) UITextField *searchTextField;

@property (nonatomic, strong) XMSearchHistoryView *searchHistoryView;

//@property (nonatomic, strong) UIView *searchHistoryView;
//@property (nonatomic, strong) UIView *historyBgView;

@property (nonatomic, strong) UIButton *screenBtn; //筛选
@property (nonatomic, strong) UIButton *allBtn; //全部
@property (nonatomic, strong) UIButton *userBtn; //用户

@property (nonatomic, strong) XMSearchScreenView *screenView;

@property (nonatomic, strong) NSMutableArray *picwordModelArr;
@property (nonatomic, strong) NSMutableArray *userModelArr;

@end

@interface XMPicwordSearchView ()

@end

@implementation XMPicwordSearchView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self creatUI];
    }
    return self;
}

- (void)creatUI {
    [self addSubview:self.navView];
    self.navView.backgroundColor = kColorHEX(0xffffff);
    [self.navView addSubview:self.searchTextField];
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(16.0) frame:CGRectMake(self.width - KScaleWidth(52.0), kNavagationBarH - 44, KScaleWidth(52.0), 44) title:@"搜索" titleColor:kColorHEX(0x333333)];
    [searchBtn addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.navView addSubview:searchBtn];
    
    [self addSubview:self.collectionView];
    [self addSubview:self.tbl];
    [self addSubview:self.screenBtn];
    [self addSubview:self.allBtn];
    [self addSubview:self.userBtn];
    
    [self addSubview:self.searchHistoryView];
    _collectionView.hidden = YES;
    _tbl.hidden = YES;
    
    [_searchHistoryView setContentWithHistoryKey:XMHISTORYSEARCHKEY];
}

- (void)setContentWithPicwordModelArr:(NSArray *)picwordModelArr
                                 page:(NSInteger)page {
    _tbl.hidden = YES;
    _collectionView.hidden = NO;
    [_collectionView.mj_header endRefreshing];
    if (page == 1) {
        [self.picwordModelArr removeAllObjects];
        [_searchHistoryView saveSearchHistoryWithSearchKey:_searchTextField.text];
    }
    if (picwordModelArr.count < 10) {
        [_collectionView.mj_footer endRefreshingWithNoMoreData];
    }
    else {
        [_collectionView.mj_footer endRefreshing];
    }
    [self.picwordModelArr addObjectsFromArray:picwordModelArr];
    [_collectionView reloadData];
    _collectionView.hidden = NO;
    _searchHistoryView.hidden = YES;
    [self endEditing:YES];
}

- (void)setContentWithUserModelArr:(NSArray *)userModelArr
                              page:(NSInteger)page {
    _tbl.hidden = NO;
    _collectionView.hidden = YES;
    [_tbl.mj_header endRefreshing];
    if (page == 0) {
        [self.userModelArr removeAllObjects];
        [self.searchHistoryView saveSearchHistoryWithSearchKey:_searchTextField.text];
    }
    if (userModelArr.count < 10) {
        [_tbl.mj_footer endRefreshingWithNoMoreData];
    }
    else {
        [_tbl.mj_footer endRefreshing];
    }
    [self.userModelArr addObjectsFromArray:userModelArr];
    [_tbl reloadData];
    [self endEditing:YES];
}

//搜索
- (void)searchAction:(UIButton *)button {
    if (_searchTextField.text.length == 0) {
        [MBProgressHUD showError:@"请输入搜索内容"];
        return;
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(picwordSearchWithSearchKey:searchType:)]) {
        [self.delegate picwordSearchWithSearchKey:_searchTextField.text searchType:_userBtn.selected ? 1 : 0];
    }
}

//筛选
- (void)screenAction:(UIButton *)button {
    [self addSubview:self.screenView];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (_userBtn.selected) {
        [dic safe_setObject:@[@"不限", @"0-100", @"100-1000", @"1000-1万", @"1万-10万", @"10万以上"] forKey:@"粉丝数量"];
    }
    else {
        [dic safe_setObject:@[@"不限", @"最新", @"最多点赞"] forKey:@"排序依据"];
        [dic safe_setObject:@[@"不限", @"一天内", @"一周内", @"一月内"] forKey:@"发布时间"];
    }
    [_screenView showWithScreenDic:dic isUser:_userBtn.selected];
    XMWeakSelf;
    _screenView.screenBlock = ^(NSString * _Nonnull keyOne, NSString * _Nonnull keyTwo) {
        if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(screenWithSearchKey:screenKeyTwo:)]) {
            [weakSelf.delegate screenWithSearchKey:keyOne
                                      screenKeyTwo:keyTwo];
        }
    };
}

//全部Tab选择
- (void)allSelectAction:(UIButton *)button {
    if (button.selected) {
        return;
    }
    button.titleLabel.font = KFontSize(18.0);
    button.selected = YES;
    XMWeakSelf;
    [UIView animateWithDuration:.3 animations:^{
        weakSelf.userBtn.titleLabel.font = KFontSize(16.0);
        weakSelf.userBtn.selected = NO;
    }];
    if (_searchTextField.text.length > 0) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(picwordSearchWithSearchKey:searchType:)]) {
            [self.delegate picwordSearchWithSearchKey:_searchTextField.text searchType:0];
        }
    }
}

//用户Tab选择
- (void)userSelectAction:(UIButton *)button {
    if (button.selected) {
        return;
    }
    button.titleLabel.font = KFontSize(18.0);
    button.selected = YES;
    
    XMWeakSelf;
    [UIView animateWithDuration:.3 animations:^{
        weakSelf.allBtn.titleLabel.font = KFontSize(16.0);
        weakSelf.allBtn.selected = NO;
    }];
    if (_searchTextField.text.length > 0) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(picwordSearchWithSearchKey:searchType:)]) {
            [self.delegate picwordSearchWithSearchKey:_searchTextField.text searchType:1];
        }
    }
}

#pragma mark - Delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _picwordModelArr.count;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout heightForItemAtIndexPath:(NSIndexPath *)indexPath {
    XMPicwordModel *picwordModel = self.picwordModelArr[indexPath.item];
    // 计算单行文本宽度
    CGFloat height = [picwordModel.title getHeightWithFont:KScaleWidth(16.0) withWidth:(self.width - 30)/2 - KScaleWidth(10.0)*2] + KScaleWidth(5.0);
    return KScaleWidth(210.0) + KScaleWidth(10.0) + height + KScaleWidth(44.0);
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    XMPicwordCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"XMPicwordCellName" forIndexPath:indexPath];
    XMPicwordModel *picwordModel = _picwordModelArr[indexPath.row];
    [cell setContentWithPicwordModel:picwordModel];
    XMWeakSelf;
    cell.likeBlock = ^{
        if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(picwordLikedWithPicwordId:)]) {
            [weakSelf.delegate picwordLikedWithPicwordId:picwordModel.objectId];
        }
    };
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    if (self.delegate && [self.delegate respondsToSelector:@selector(checkPicwordDetailWithPicwordId:)]) {
        XMPicwordModel *picwordModel = _picwordModelArr[indexPath.row];
        [self.delegate checkPicwordDetailWithPicwordId:picwordModel.objectId];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.text.length > 0) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(picwordSearchWithSearchKey:searchType:)]) {
            [self.delegate picwordSearchWithSearchKey:textField.text
                                           searchType:_userBtn.selected ? 1 : 0];
        }
    }
    return YES;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.userModelArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return KScaleWidth(77.0);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XMAddFriendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XMAddFriendCellName" forIndexPath:indexPath];
    [cell setContentWithFriendModel:self.userModelArr[indexPath.row]];
    XMWeakSelf;
    cell.attentionBlock = ^{
        if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(userAttentionWithUserId:attentionStatus:)]) {
            XMFriendModel *friendModel = weakSelf.userModelArr[indexPath.row];
            [weakSelf.delegate userAttentionWithUserId:friendModel.userId attentionStatus:friendModel.status];
        }
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.delegate && [self.delegate respondsToSelector:@selector(checkUserDetailWithUserId:)]) {
        XMFriendModel *friendModel = self.userModelArr[indexPath.row];
        [self.delegate checkUserDetailWithUserId:friendModel.userId];
    }
}

#pragma mark - Init
- (UITextField *)searchTextField {
    if (!_searchTextField) {
        _searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(44, kNavagationBarH - 44 + (44 - KScaleWidth(36.0))/2, self.width - 44 - KScaleWidth(52.0), KScaleWidth(36.0))];
        _searchTextField.font = KFontSize(13.0);
        _searchTextField.returnKeyType = UIReturnKeySearch;
        _searchTextField.placeholder = @"搜索内容/用户";
        _searchTextField.delegate = self;
        _searchTextField.backgroundColor = kColorHEX(0xF6F6F6);
        [_searchTextField setCornerRadius:_searchTextField.height/2];
        
        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScaleWidth(30.0), _searchTextField.height)];
        UIImageView *searchIcon = [[UIImageView alloc] initWithFrame:CGRectMake((leftView.width - KScaleWidth(14.0))/2, 0, KScaleWidth(14.0), _searchTextField.height)];
        searchIcon.contentMode = UIViewContentModeScaleAspectFit;
        searchIcon.image = ImageNamed(@"mine_search_icon");
        [leftView addSubview:searchIcon];
        _searchTextField.leftView = leftView;
        _searchTextField.leftViewMode = UITextFieldViewModeAlways;
    }
    return _searchTextField;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        WaterfallFlowLayout *layout = [[WaterfallFlowLayout alloc] init];
        layout.delegate = self;
        layout.columnCount = 2;
        layout.columnSpacing = 10;
        layout.rowSpacing = 10;
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        
        // 创建 UICollectionView
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, kNavagationBarH + KScaleWidth(56.0), self.width, self.height - kNavagationBarH - KScaleWidth(56.0)) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = kColorHEX(0xF0F0F0);
        [_collectionView registerClass:[XMPicwordCell class] forCellWithReuseIdentifier:@"XMPicwordCellName"];
        layout.sectionInset = UIEdgeInsetsMake(0, layout.sectionInset.left, layout.sectionInset.bottom, layout.sectionInset.right);
        
        XMWeakSelf;
        _collectionView.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(refreshData)]) {
                [weakSelf.delegate refreshData];
            }
        }];
        _collectionView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(loadMoreData)]) {
                [weakSelf.delegate loadMoreData];
            }
        }];
        
    }
    return _collectionView;
}

- (UITableView *)tbl {
    if (!_tbl) {
        _tbl = [[UITableView alloc] initWithFrame:self.collectionView.frame];
        _tbl.delegate = self;
        _tbl.dataSource = self;
        [_tbl registerClass:[XMAddFriendCell class] forCellReuseIdentifier:@"XMAddFriendCellName"];
        if (@available(iOS 15.0, *)) {
            _tbl.sectionHeaderTopPadding = 0;
        } else {
            _tbl.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            // Fallback on earlier versions
        }
        XMWeakSelf;
        _tbl.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(refreshData)]) {
                [weakSelf.delegate refreshData];
            }
        }];
        _tbl.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(loadMoreData)]) {
                [weakSelf.delegate loadMoreData];
            }
        }];
    }
    return _tbl;
}

- (XMSearchHistoryView *)searchHistoryView {
    if (!_searchHistoryView) {
        _searchHistoryView = [[XMSearchHistoryView alloc] initWithFrame:CGRectMake(0, kNavagationBarH, self.width, KScaleWidth(140.0))];
        XMWeakSelf;
        _searchHistoryView.historyItemSelectBlock = ^(NSString * _Nonnull historyStr) {
            weakSelf.searchTextField.text = historyStr;
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(picwordSearchWithSearchKey:searchType:)]) {
                [weakSelf.delegate picwordSearchWithSearchKey:historyStr
                                                   searchType:weakSelf.userBtn.selected ? 1 : 0];
            }
        };
    }
    return _searchHistoryView;
}

- (UIButton *)screenBtn {
    if (!_screenBtn) {
        _screenBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(14.0) frame:CGRectMake(self.width - KScaleWidth(64.0), kNavagationBarH + KScaleWidth(10.0), KScaleWidth(64.0), KScaleWidth(46.0)) title:@"筛选" titleColor:kColorHEX(0xE05D4D) image:@"find_search_screen_icon"];
        [_screenBtn addTarget:self action:@selector(screenAction:) forControlEvents:UIControlEventTouchUpInside];
        [_screenBtn layoutButtonWithEdgeInsetsStyle:CSButtonEdgeInsetsStyleRight ImageTitleSpace:KScaleWidth(5.0)];
    }
    return _screenBtn;
}

- (UIButton *)allBtn {
    if (!_allBtn) {
        _allBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(18.0) frame:CGRectMake(KScaleWidth(7.0), kNavagationBarH + KScaleWidth(10.0), KScaleWidth(54.0), KScaleWidth(46.0)) title:@"全部" titleColor:kColorHEX(0x666666)];
        [_allBtn setTitleColor:kColorHEX(0x333333) forState:UIControlStateSelected];
        [_allBtn addTarget:self action:@selector(allSelectAction:) forControlEvents:UIControlEventTouchUpInside];
        _allBtn.selected = YES;
    }
    return _allBtn;
}

- (UIButton *)userBtn {
    if (!_userBtn) {
        _userBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(16.0) frame:CGRectMake(self.allBtn.maxX, _allBtn.y, _allBtn.width, _allBtn.height) title:@"用户" titleColor:kColorHEX(0x666666)];
        [_userBtn addTarget:self action:@selector(userSelectAction:) forControlEvents:UIControlEventTouchUpInside];
        [_userBtn setTitleColor:kColorHEX(0x333333) forState:UIControlStateSelected];
    }
    return _userBtn;
}

- (XMSearchScreenView *)screenView {
    if (!_screenView) {
        _screenView = [[XMSearchScreenView alloc] initWithFrame:CGRectMake(0, kNavagationBarH, self.width, self.height - kNavagationBarH)];
    }
    return _screenView;
}

- (NSMutableArray *)picwordModelArr {
    if (!_picwordModelArr) {
        _picwordModelArr = [NSMutableArray array];
    }
    return _picwordModelArr;
}

- (NSMutableArray *)userModelArr {
    if (!_userModelArr) {
        _userModelArr = [NSMutableArray array];
    }
    return _userModelArr;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
